import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';

class CheckboxWrap<E, K> extends HookWidget {
  final List<E> elements;
  final K Function(E e) getKey;
  final String Function(E e) getLabel;
  final List<K> selectedKeys;
  final void Function(List<K> keys) onChange;

  const CheckboxWrap({
    Key? key,
    required this.elements,
    required this.getKey,
    required this.getLabel,
    required this.selectedKeys,
    required this.onChange,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Wrap(
      spacing: 10,
      children: elements.map((e) {
        var checked = selectedKeys.contains(getKey(e));
        return Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              getLabel(e),
              style: Theme.of(context).textTheme.labelLarge,
            ),
            Checkbox(
              value: checked,
              onChanged: (value) {
                if (value==true) {
                  onChange(selectedKeys.toList()..add(getKey(e)));
                } else {
                  onChange(selectedKeys.toList()
                    ..removeWhere(
                      (element) => element == getKey(e),
                    ));
                }
              },
            ),
          ],
        );
      }).toList(),
    );
  }
}
